Popular Searches
Popular Course Categories
Popular Courses

Exception Handling

Selenium with Java

Waits with Java in Selenium

Waits are one of the most important concepts in Selenium automation because modern web applications are dynamic. Elements may load after the page is displayed, AJAX requests may update the DOM, buttons may become clickable only after an animation finishes, loaders may temporarily cover elements, and content may appear asynchronously.

Selenium waits provide synchronization between the automation script and the application under test. Instead of assuming that an element is immediately ready, waits allow Selenium to wait for a required condition before continuing with the next action.

In Java Selenium automation, the most commonly used synchronization mechanisms are Implicit Wait, Explicit Wait, and Fluent Wait. Thread.sleep() is also available in Java, but it is a fixed delay rather than a condition-based Selenium wait and should generally not be the primary synchronization technique.

Course Resources: Selenium Training | Register for Course Demo


1. What Are Waits in Selenium?

Waits in Selenium are synchronization mechanisms that allow WebDriver to pause execution until a specified condition is satisfied or a configured timeout is reached.

For example, if a login button appears only after a page finishes loading, Selenium should not immediately attempt to click it. Instead, the test can wait until the button becomes clickable.

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("login")

    )

).click();

2. Why Are Waits Important in Selenium?

Web applications rarely behave like static HTML pages. JavaScript, AJAX, APIs, animations, lazy loading, dynamic components, and asynchronous operations can change the page after the initial HTML has loaded.

  • Synchronizes automation with the application.
  • Handles dynamically loaded elements.
  • Reduces timing-related failures.
  • Improves test stability.
  • Helps interact with elements only when they are ready.
  • Handles loaders and overlays.
  • Supports dynamic text and page state validation.
  • Helps synchronize frames, alerts, windows, and other browser states.

3. Synchronization in Selenium

Synchronization means making sure that the Selenium test performs an operation at the appropriate time relative to the application's state.

Test Starts

    |

    v

Open Web Page

    |

    v

Application Loads

    |

    v

Dynamic Operation

    |

    v

Element Ready?

   / \

 No   Yes

 |     |

 |     v

 |   Perform Action

 |

 v

Keep Waiting

    |

    v

Timeout?

   / \

 No   Yes

 |     |

 v     v

Continue  TimeoutException

4. Types of Waits in Selenium

Wait TypeDescriptionMain Usage
Implicit WaitSets a default waiting period for element lookup.Basic element-location synchronization.
Explicit WaitWaits for a specific condition.Dynamic elements and application states.
Fluent WaitProvides configurable timeout, polling interval, and ignored exceptions.Advanced custom synchronization.
Thread.sleep()Pauses execution for a fixed duration.Occasional debugging or special cases, not ideal for normal synchronization.

5. Implicit Wait

An implicit wait tells WebDriver to wait for a specified amount of time when trying to locate an element if it is not immediately available.

The implicit wait is configured once and applies globally to element location operations performed through that WebDriver instance.

6. Implicit Wait Syntax

driver.manage().timeouts().implicitlyWait(

    Duration.ofSeconds(10)

);

7. Complete Implicit Wait Example

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class ImplicitWaitExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.manage().window().maximize();

 

        driver.manage().timeouts().implicitlyWait(

            Duration.ofSeconds(10)

        );

 

        driver.get("https://example.com");

 

        driver.findElement(

            By.id("username")

        ).sendKeys("admin");

 

        driver.quit();

    }

}

8. How Implicit Wait Works

findElement()

     |

     v

Element Found?

   / \

 Yes  No

  |    |

  v    v

Return  Wait

Element  |

         v

    Element Appears?

       / \

     Yes  No

      |    |

      v    v

    Return Timeout

    Element

9. Limitations of Implicit Wait

  • Primarily affects element location.
  • It does not specifically wait for an element to become clickable.
  • It does not directly wait for text to change.
  • It does not directly wait for a URL condition.
  • It does not provide the same condition-level control as explicit waits.
  • Using large implicit wait values can make failures slower to diagnose.

10. Explicit Wait

An explicit wait waits for a particular condition to become true before allowing the test to continue.

Explicit waits are especially useful for modern dynamic applications because different elements may become ready at different times.

11. WebDriverWait

WebDriverWait is the most commonly used Selenium Java class for explicit waits. It allows a test to wait until a specified expected condition is satisfied or the timeout expires.

12. WebDriverWait Syntax in Selenium 4

WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

    );

13. Basic Explicit Wait Example

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement username = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("username")

    )

);

 

username.sendKeys("admin");

14. Explicit Wait Flow

Create WebDriverWait

        |

        v

Specify Timeout

        |

        v

Specify Condition

        |

        v

Check Condition

     /      \

 False       True

   |           |

   v           v

Wait/Poll   Continue

   |

   v

Timeout?

 /     \

No      Yes

|        |

v        v

Check    TimeoutException

15. ExpectedConditions

ExpectedConditions provides commonly used conditions for Selenium explicit waits.

Instead of manually checking every browser state, automation engineers can use predefined conditions such as element visibility, clickability, text presence, URL changes, title changes, alerts, frames, windows, and element collections.

16. Common Expected Conditions

ConditionPurpose
presenceOfElementLocated()Waits until an element exists in the DOM.
visibilityOfElementLocated()Waits until an element exists and is visible.
elementToBeClickable()Waits until an element is suitable for clicking.
invisibilityOfElementLocated()Waits until an element becomes invisible or is no longer present.
textToBePresentInElementLocated()Waits until expected text appears.
titleIs()Waits for an exact page title.
titleContains()Waits for a title containing specific text.
urlToBe()Waits for an exact URL.
urlContains()Waits for a URL containing specific text.
alertIsPresent()Waits for a browser alert.
frameToBeAvailableAndSwitchToIt()Waits for a frame and switches into it.
stalenessOf()Waits until an element becomes stale.
refreshed()Re-evaluates a condition after a refresh or DOM change.

17. presenceOfElementLocated()

This condition waits until an element is present in the DOM. Presence does not necessarily mean that the element is visible or ready for interaction.

WebElement element = wait.until(

    ExpectedConditions.presenceOfElementLocated(

        By.id("username")

    )

);

18. Presence vs Visibility

PresenceVisibility
Element exists in the DOM.Element exists and is visible.
Does not guarantee user-visible interaction.More suitable for visible UI elements.
Useful for DOM existence checks.Useful before many user interactions.

19. visibilityOfElementLocated()

This condition waits until an element is located and visible.

WebElement username = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("username")

    )

);

 

username.sendKeys("admin");

20. elementToBeClickable()

elementToBeClickable() is useful when an element needs to be clicked after becoming ready for interaction.

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("login")

    )

);

 

loginButton.click();

21. Waiting for a Button to Become Clickable

wait.until(

    ExpectedConditions.elementToBeClickable(

        By.cssSelector("button[type='submit']")

    )

).click();

22. invisibilityOfElementLocated()

This condition is useful for loaders, spinners, overlays, progress indicators, and temporary elements that must disappear before continuing.

wait.until(

    ExpectedConditions.invisibilityOfElementLocated(

        By.id("loader")

    )

);

23. Waiting for a Loading Spinner

wait.until(

    ExpectedConditions.invisibilityOfElementLocated(

        By.cssSelector(".loading-spinner")

    )

);

 

wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("submit")

    )

).click();

24. textToBePresentInElementLocated()

This condition waits until specific text is present inside an element.

wait.until(

    ExpectedConditions.textToBePresentInElementLocated(

        By.id("status"),

        "Completed"

    )

);

25. Waiting for a Success Message

wait.until(

    ExpectedConditions.textToBePresentInElementLocated(

        By.id("message"),

        "Registration successful"

    )

);

26. textToBePresentInElement()

If a WebElement reference is already available, Selenium can wait for specific text inside that element.

WebElement status =

    driver.findElement(By.id("status"));

 

wait.until(

    ExpectedConditions.textToBePresentInElement(

        status,

        "Completed"

    )

);

27. titleIs()

titleIs() waits until the page title exactly matches the expected title.

wait.until(

    ExpectedConditions.titleIs(

        "Dashboard"

    )

);

28. titleContains()

titleContains() waits until the page title contains the specified text.

wait.until(

    ExpectedConditions.titleContains(

        "Dashboard"

    )

);

29. urlToBe()

urlToBe() waits for the browser URL to exactly match the specified URL.

wait.until(

    ExpectedConditions.urlToBe(

        "https://example.com/dashboard"

    )

);

30. urlContains()

urlContains() waits until the current URL contains the specified text.

wait.until(

    ExpectedConditions.urlContains(

        "/dashboard"

    )

);

31. Waiting for an Alert

JavaScript alerts may appear dynamically. Instead of immediately switching to an alert, an explicit wait can be used.

Alert alert = wait.until(

    ExpectedConditions.alertIsPresent()

);

 

System.out.println(

    alert.getText()

);

 

alert.accept();

32. Waiting for an Iframe

Frames may load after the main page. Selenium can wait until a frame is available and switch to it.

wait.until(

    ExpectedConditions.frameToBeAvailableAndSwitchToIt(

        By.id("paymentFrame")

    )

);

33. Returning from an Iframe

driver.switchTo().defaultContent();

34. Waiting for a New Window

When a click opens a new tab or window, the test can wait until the expected number of browser windows exists.

String originalWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("openWindow")

).click();

 

wait.until(

    ExpectedConditions.numberOfWindowsToBe(2)

);

 

for (String handle : driver.getWindowHandles()) {

 

    if (!handle.equals(originalWindow)) {

        driver.switchTo().window(handle);

        break;

    }

}

35. stalenessOf()

stalenessOf() waits until a previously located element is no longer attached to the DOM.

WebElement oldElement =

    driver.findElement(By.id("result"));

 

wait.until(

    ExpectedConditions.stalenessOf(oldElement)

);

36. Why Staleness Wait Is Useful

Dynamic applications may replace elements after AJAX calls, searches, filtering, pagination, or component re-rendering. Waiting for the old element to become stale can help synchronize the test with the DOM update.

37. refreshed()

refreshed() can be useful when a condition needs to be evaluated again after a DOM refresh or replacement.

WebElement result = wait.until(

    ExpectedConditions.refreshed(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("result")

        )

    )

);

 

result.click();

38. Waiting for Multiple Elements

Selenium provides conditions for collections of elements, which can be useful for lists, search results, product cards, table rows, and menu items.

List<WebElement> products = wait.until(

    ExpectedConditions.presenceOfAllElementsLocatedBy(

        By.cssSelector(".product")

    )

);

 

System.out.println(

    "Products: " + products.size()

);

39. visibilityOfAllElementsLocatedBy()

List<WebElement> products = wait.until(

    ExpectedConditions.visibilityOfAllElementsLocatedBy(

        By.cssSelector(".product")

    )

);

40. Waiting for a Specific Number of Elements

wait.until(

    ExpectedConditions.numberOfElementsToBe(

        By.cssSelector(".product"),

        10

    )

);

41. Waiting for More Than a Specific Number of Elements

wait.until(

    ExpectedConditions.numberOfElementsToBeMoreThan(

        By.cssSelector(".product"),

        5

    )

);

42. Waiting for Fewer Than a Specific Number of Elements

wait.until(

    ExpectedConditions.numberOfElementsToBeLessThan(

        By.cssSelector(".product"),

        10

    )

);

43. Waiting for an Attribute

Explicit waits can also be used when an element's attribute must reach an expected value.

wait.until(

    ExpectedConditions.attributeToBe(

        By.id("status"),

        "data-state",

        "completed"

    )

);

44. Waiting for an Attribute to Contain Text

wait.until(

    ExpectedConditions.attributeContains(

        By.id("status"),

        "class",

        "completed"

    )

);

45. FluentWait

FluentWait provides advanced control over synchronization. It allows the automation engineer to configure the maximum timeout, polling interval, ignored exceptions, and custom timeout behavior.

46. FluentWait Syntax

Wait<WebDriver> wait =

    new FluentWait<>(driver)

        .withTimeout(Duration.ofSeconds(20))

        .pollingEvery(Duration.ofMillis(500))

        .ignoring(NoSuchElementException.class);

47. FluentWait Example

Wait<WebDriver> wait =

    new FluentWait<>(driver)

        .withTimeout(Duration.ofSeconds(20))

        .pollingEvery(Duration.ofMillis(500))

        .ignoring(NoSuchElementException.class);

 

WebElement element = wait.until(

    driver -> driver.findElement(

        By.id("dynamicElement")

    )

);

48. FluentWait Polling

Polling determines how frequently Selenium checks the specified condition.

Timeout = 20 seconds

Polling = 500 milliseconds

 

Check

  |

  v

Condition?

  |

  +-- No --> Wait 500 ms --> Check Again

  |

  +-- Yes --> Continue

49. FluentWait with Custom Condition

Wait<WebDriver> wait =

    new FluentWait<>(driver)

        .withTimeout(Duration.ofSeconds(20))

        .pollingEvery(Duration.ofSeconds(1))

        .ignoring(NoSuchElementException.class);

 

String status = wait.until(

    driver -> {

        String text =

            driver.findElement(

                By.id("status")

            ).getText();

 

        return text.equals("Completed")

            ? text

            : null;

    }

);

50. Custom Wait Using Lambda

Java lambda expressions can be used to create condition-based waits without relying only on predefined ExpectedConditions.

WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

    );

 

wait.until(

    driver ->

        "Completed".equals(

            driver.findElement(

                By.id("status")

            ).getText()

        )

);

51. Custom Wait for Element Text

wait.until(

    driver -> {

        WebElement element =

            driver.findElement(

                By.id("orderStatus")

            );

 

        return element.getText()

            .contains("Delivered");

    }

);

52. Custom Wait for Attribute

wait.until(

    driver -> {

        WebElement element =

            driver.findElement(

                By.id("submit");

 

        return "enabled".equals(

            element.getAttribute("data-state")

        );

    }

);

53. Thread.sleep()

Thread.sleep() pauses the Java thread for a fixed amount of time. It does not understand the state of the web page.

Thread.sleep(5000);

The problem with a fixed sleep is that the test always waits the full duration even if the application becomes ready earlier. If the application takes longer than the sleep duration, the test can still fail.

54. Thread.sleep() vs Explicit Wait

Thread.sleep()Explicit Wait
Fixed delay.Condition-based synchronization.
Does not check application state.Checks a specified condition.
May waste execution time.Continues as soon as condition is satisfied.
Can make tests slower.Usually more efficient for dynamic applications.
Not Selenium-specific.Designed for WebDriver synchronization.

55. Implicit Wait vs Explicit Wait

Implicit WaitExplicit Wait
Global WebDriver setting.Applied to a specific condition.
Mainly affects element lookup.Can wait for many application states.
Simple configuration.More flexible.
Less precise.More precise.
Configured once.Created and used where required.

56. Explicit Wait vs Fluent Wait

Explicit WaitFluent Wait
Usually implemented with WebDriverWait.Implemented using FluentWait.
Simple condition-based waiting.Advanced configurable waiting.
Convenient for common ExpectedConditions.Useful for custom polling and exception handling.
Less configuration required.More configuration options.

57. Should Implicit and Explicit Waits Be Mixed?

Mixing implicit and explicit waits can make timing behavior difficult to reason about. A test framework should generally use a consistent synchronization strategy and avoid unnecessary combinations of different timeout mechanisms.

58. Waiting for AJAX Content

AJAX operations can update the page without a full browser navigation. An element may exist initially but its content may change later.

wait.until(

    ExpectedConditions.textToBePresentInElementLocated(

        By.id("result"),

        "Data loaded"

    )

);

59. Waiting for a Loader to Disappear

wait.until(

    ExpectedConditions.invisibilityOfElementLocated(

        By.cssSelector(".loader")

    )

);

 

wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("submit")

    )

).click();

60. Waiting for a Search Result

driver.findElement(

    By.id("search")

).sendKeys("Laptop");

 

driver.findElement(

    By.id("searchButton")

).click();

 

wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.cssSelector(".search-result")

    )

);

61. Waiting for an E-Commerce Cart Update

wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("addToCart")

    )

).click();

 

wait.until(

    ExpectedConditions.textToBePresentInElementLocated(

        By.id("cartCount"),

        "1"

    )

);

62. Waiting for Login Navigation

wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("login")

    )

).click();

 

wait.until(

    ExpectedConditions.urlContains(

        "/dashboard"

    )

);

63. Waiting for a Success Message

wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("successMessage")

    )

);

 

wait.until(

    ExpectedConditions.textToBePresentInElementLocated(

        By.id("successMessage"),

        "Success"

    )

);

64. Waiting for a Disabled Button to Become Enabled

Sometimes an application changes an element's state after validation or an asynchronous operation.

wait.until(

    driver -> {

        WebElement button =

            driver.findElement(

                By.id("submit")

            );

 

        return button.isEnabled();

    }

);

 

driver.findElement(

    By.id("submit")

).click();

65. Waiting for a Checkbox to Be Selected

wait.until(

    ExpectedConditions.elementToBeSelected(

        By.id("terms")

    )

);

66. Waiting for Selection State

wait.until(

    ExpectedConditions.elementSelectionStateToBe(

        By.id("terms"),

        true

    )

);

67. Waiting for an Element to Disappear

wait.until(

    ExpectedConditions.invisibilityOfElementLocated(

        By.id("temporaryMessage")

    )

);

68. Handling TimeoutException

When an explicit wait reaches its configured timeout without satisfying the condition, Selenium throws a TimeoutException.

try {

 

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("dashboard")

        )

    );

 

} catch (TimeoutException e) {

 

    System.out.println(

        "Dashboard did not appear."

    );

 

    e.printStackTrace();

}

69. Common Causes of TimeoutException

  • Incorrect locator.
  • Element never appears.
  • Element is inside an iframe.
  • Expected condition is incorrect.
  • Application is slower than expected.
  • Loader or overlay is blocking the UI.
  • Expected text is incorrect.
  • Application error prevents the expected state.
  • Timeout value is too short for the environment.

70. Wait for Frame and Handle Timeout

try {

 

    wait.until(

        ExpectedConditions.frameToBeAvailableAndSwitchToIt(

            By.id("paymentFrame")

        )

    );

 

} catch (TimeoutException e) {

 

    System.out.println(

        "Payment frame did not become available."

    );

}

71. Wait for Alert and Handle Timeout

try {

 

    Alert alert = wait.until(

        ExpectedConditions.alertIsPresent()

    );

 

    alert.accept();

 

} catch (TimeoutException e) {

 

    System.out.println(

        "Expected alert did not appear."

    );

}

72. Wait Utility Class

In a professional automation framework, wait logic is often centralized in a reusable utility class.

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class WaitUtils {

 

    private WebDriver driver;

    private WebDriverWait wait;

 

    public WaitUtils(WebDriver driver) {

 

        this.driver = driver;

 

        this.wait =

            new WebDriverWait(

                driver,

                Duration.ofSeconds(10)

            );

    }

 

    public WebElement waitForVisibility(By locator) {

 

        return wait.until(

            ExpectedConditions.visibilityOfElementLocated(

                locator

            )

        );

    }

 

    public WebElement waitForClickable(By locator) {

 

        return wait.until(

            ExpectedConditions.elementToBeClickable(

                locator

            )

        );

    }

 

    public void waitForInvisibility(By locator) {

 

        wait.until(

            ExpectedConditions.invisibilityOfElementLocated(

                locator

            )

        );

    }

 

    public void waitForText(By locator, String text) {

 

        wait.until(

            ExpectedConditions.textToBePresentInElementLocated(

                locator,

                text

            )

        );

    }

}

73. Using WaitUtils

WaitUtils waitUtils =

    new WaitUtils(driver);

 

waitUtils.waitForVisibility(

    By.id("username")

).sendKeys("admin");

 

waitUtils.waitForClickable(

    By.id("login")

).click();

 

waitUtils.waitForText(

    By.id("message"),

    "Login successful"

);

74. Waits in Page Object Model

Waits are commonly placed inside Page Object methods so that test cases remain readable and business-focused.

public class LoginPage {

 

    private WebDriver driver;

    private WebDriverWait wait;

 

    private By username =

        By.id("username");

 

    private By password =

        By.id("password");

 

    private By loginButton =

        By.id("login");

 

    public LoginPage(WebDriver driver) {

 

        this.driver = driver;

 

        this.wait =

            new WebDriverWait(

                driver,

                Duration.ofSeconds(10)

            );

    }

 

    public void login(

        String user,

        String pass

    ) {

 

        wait.until(

            ExpectedConditions.visibilityOfElementLocated(

                username

            )

        ).sendKeys(user);

 

        wait.until(

            ExpectedConditions.visibilityOfElementLocated(

                password

            )

        ).sendKeys(pass);

 

        wait.until(

            ExpectedConditions.elementToBeClickable(

                loginButton

            )

        ).click();

    }

}

75. Test Case Using Page Object and Waits

LoginPage loginPage =

    new LoginPage(driver);

 

loginPage.login(

    "admin",

    "admin123"

);

 

WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

    );

 

wait.until(

    ExpectedConditions.urlContains(

        "/dashboard"

    )

);

76. Practical Login Flow

Open Login Page

       |

       v

Wait for Username

       |

       v

Enter Username

       |

       v

Wait for Password

       |

       v

Enter Password

       |

       v

Wait for Login Button

       |

       v

Click Login

       |

       v

Wait for Dashboard URL

       |

       v

Wait for Dashboard Element

       |

       v

Login Successful

77. Practical Login Example with Explicit Wait

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class LoginWaitExample {

 

    public static void main(String[] args) {

 

        WebDriver driver =

            new ChromeDriver();

 

        try {

 

            driver.manage()

                .window()

                .maximize();

 

            driver.get(

                "https://example.com/login"

            );

 

            WebDriverWait wait =

                new WebDriverWait(

                    driver,

                    Duration.ofSeconds(15)

                );

 

            wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.id("username")

                )

            ).sendKeys("admin");

 

            wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.id("password")

                )

            ).sendKeys("admin123");

 

            wait.until(

                ExpectedConditions.elementToBeClickable(

                    By.id("login")

                )

            ).click();

 

            wait.until(

                ExpectedConditions.urlContains(

                    "/dashboard"

                )

            );

 

            wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.id("dashboard")

                )

            );

 

            System.out.println(

                "Login successful."

            );

 

        } finally {

 

            driver.quit();

        }

    }

}

78. Practical E-Commerce Wait Flow

Open Product Page

       |

       v

Wait for Product

       |

       v

Click Add to Cart

       |

       v

Wait for Cart Count

       |

       v

Open Cart

       |

       v

Wait for Cart Items

       |

       v

Click Checkout

       |

       v

Wait for Payment Frame

       |

       v

Enter Payment Details

       |

       v

Wait for Confirmation

       |

       v

Verify Order Success

79. E-Commerce Wait Example

wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.cssSelector(".product-card")

    )

);

 

wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("addToCart")

    )

).click();

 

wait.until(

    ExpectedConditions.textToBePresentInElementLocated(

        By.id("cartCount"),

        "1"

    )

);

 

wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("checkout")

    )

).click();

 

wait.until(

    ExpectedConditions.frameToBeAvailableAndSwitchToIt(

        By.id("paymentFrame")

    )

);

 

wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("cardNumber")

    )

).sendKeys("TEST_CARD");

 

driver.switchTo().defaultContent();

 

wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("orderSuccess")

    )

);

80. Waits for Dynamic Tables

Dynamic tables may load rows asynchronously. Instead of using a fixed delay, wait until the required number of rows becomes available.

wait.until(

    ExpectedConditions.numberOfElementsToBeMoreThan(

        By.cssSelector("table tbody tr"),

        0

    )

);

81. Waits for Search Suggestions

driver.findElement(

    By.id("search")

).sendKeys("Selenium");

 

wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.cssSelector(".suggestion")

    )

);

82. Waits for Auto-Save

wait.until(

    ExpectedConditions.textToBePresentInElementLocated(

        By.id("saveStatus"),

        "Saved"

    )

);

83. Waits for a Modal to Appear

wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("confirmationModal")

    )

);

84. Waits for a Modal to Disappear

wait.until(

    ExpectedConditions.invisibilityOfElementLocated(

        By.id("confirmationModal")

    )

);

85. Waits and JavaScript Executor

Sometimes an application exposes a JavaScript state that can be used as part of a custom wait. This should be used only when a suitable DOM-based condition is not sufficient.

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(20)

    );

 

wait.until(

    driver -> {

        Object readyState =

            js.executeScript(

                "return document.readyState;"

            );

 

        return "complete".equals(

            readyState

        );

    }

);

86. Page Load State Wait

Waiting for document.readyState to become complete can be useful in selected scenarios, but it does not guarantee that every AJAX operation or dynamic component on the page has finished loading.

wait.until(

    driver -> {

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        return "complete".equals(

            js.executeScript(

                "return document.readyState;"

            )

        );

    }

);

87. Waiting for Network-Driven UI

For applications that update the interface after API calls, the best wait is generally based on the visible application state that proves the operation completed.

wait.until(

    ExpectedConditions.textToBePresentInElementLocated(

        By.id("status"),

        "Data loaded"

    )

);

88. Why Condition-Based Waits Are Better

  • They synchronize with actual application state.
  • They can finish immediately when the condition is satisfied.
  • They reduce unnecessary test execution time.
  • They make test intent clearer.
  • They are easier to maintain than scattered fixed delays.

89. Common Wait-Related Exceptions

ExceptionPossible CausePossible Solution
TimeoutExceptionCondition not satisfied before timeout.Check locator, condition, application state, and timeout.
NoSuchElementExceptionElement cannot be located.Check locator, timing, frame, and page.
StaleElementReferenceExceptionDOM changed after locating element.Re-locate the element or use an appropriate refreshed condition.
ElementNotInteractableExceptionElement is not currently interactable.Wait for visibility or appropriate state.
ElementClickInterceptedExceptionAnother element blocks the click.Wait for overlay or blocking element to disappear.

90. Common Mistakes with Selenium Waits

  • Using Thread.sleep() everywhere.
  • Using very large timeout values without investigating the actual problem.
  • Using presence when visibility is required.
  • Trying to click immediately after locating a dynamic element.
  • Ignoring overlays and loaders.
  • Using incorrect locators and increasing the timeout instead.
  • Mixing multiple wait strategies without understanding their behavior.
  • Using implicit waits as a replacement for all explicit conditions.
  • Waiting for an arbitrary amount of time instead of an application state.
  • Not handling stale elements in frequently re-rendered applications.

91. Best Practices for Selenium Waits

  • Prefer condition-based synchronization.
  • Use explicit waits for dynamic application behavior.
  • Choose the most appropriate ExpectedCondition.
  • Use visibility when the element must be visible.
  • Use elementToBeClickable() before important click operations.
  • Wait for loaders and overlays to disappear.
  • Wait for meaningful text or application state after asynchronous operations.
  • Use FluentWait when custom polling or ignored exceptions are genuinely required.
  • Keep wait utilities reusable in large frameworks.
  • Keep timeout values reasonable and environment-aware.
  • Do not use waits to hide incorrect locators or application defects.
  • Avoid unnecessary Thread.sleep() calls.

92. Wait Strategy for a Professional Selenium Framework

Page Object

    |

    v

Reusable Wait Utility

    |

    v

Explicit Condition

    |

    +-- Visibility

    |

    +-- Clickability

    |

    +-- Text

    |

    +-- URL

    |

    +-- Title

    |

    +-- Alert

    |

    +-- Frame

    |

    +-- Window

    |

    +-- DOM State

    |

    v

Perform Action

    |

    v

Validate Result

93. Wait Selection Guide

RequirementRecommended Wait
Element should exist in DOMpresenceOfElementLocated()
Element should be visiblevisibilityOfElementLocated()
Button should be ready for clickelementToBeClickable()
Loader should disappearinvisibilityOfElementLocated()
Specific text should appeartextToBePresentInElementLocated()
Page title should changetitleIs() / titleContains()
URL should changeurlToBe() / urlContains()
Alert should appearalertIsPresent()
Frame should become availableframeToBeAvailableAndSwitchToIt()
DOM element should become stalestalenessOf()
Dynamic DOM should be refreshedrefreshed()
Custom application conditionWebDriverWait / FluentWait with lambda

94. Complete Selenium Wait Program

import java.time.Duration;

import java.util.List;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class SeleniumWaits {

 

    public static void main(String[] args) {

 

        WebDriver driver =

            new ChromeDriver();

 

        try {

 

            driver.manage()

                .window()

                .maximize();

 

            driver.get(

                "https://www.selenium.dev/selenium/web/web-form.html"

            );

 

            WebDriverWait wait =

                new WebDriverWait(

                    driver,

                    Duration.ofSeconds(10)

                );

 

            WebElement textBox = wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.name("my-text")

                )

            );

 

            textBox.clear();

            textBox.sendKeys(

                "Selenium Waits with Java"

            );

 

            WebElement submitButton = wait.until(

                ExpectedConditions.elementToBeClickable(

                    By.cssSelector("button")

                )

            );

 

            submitButton.click();

 

            WebElement message = wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.id("message")

                )

            );

 

            System.out.println(

                "Message: " + message.getText()

            );

 

            wait.until(

                ExpectedConditions.textToBePresentInElementLocated(

                    By.id("message"),

                    "Received"

                )

            );

 

            System.out.println(

                "Expected message received."

            );

 

        } finally {

 

            driver.quit();

        }

    }

}

95. Interview Question: What Is a Wait in Selenium?

A wait is a synchronization mechanism that allows Selenium to wait until an expected condition is satisfied or a timeout is reached.

96. Interview Question: What Are the Types of Waits in Selenium?

The commonly used Selenium wait mechanisms are implicit wait, explicit wait, and fluent wait. Java's Thread.sleep() is a fixed delay and is not a condition-based Selenium wait.

97. Interview Question: What Is Implicit Wait?

Implicit wait configures a default waiting period for WebDriver element lookup operations when elements are not immediately available.

98. Interview Question: What Is Explicit Wait?

Explicit wait waits for a specific condition, such as visibility, clickability, text, URL, title, alert, or frame availability.

99. Interview Question: What Is WebDriverWait?

WebDriverWait is a Selenium Java wait implementation used to wait for conditions involving WebDriver until the condition succeeds or the timeout is reached.

100. Interview Question: What Is FluentWait?

FluentWait provides configurable timeout, polling interval, and ignored exception behavior, making it suitable for advanced custom synchronization.

101. Interview Question: What Is ExpectedConditions?

ExpectedConditions is a Selenium utility class containing predefined conditions that can be used with explicit waits.

102. Interview Question: Difference Between Presence and Visibility?

Presence means that the element exists in the DOM. Visibility means that the element exists and is visible. An element can be present without being suitable for visible user interaction.

103. Interview Question: Difference Between Visibility and Clickability?

Visibility checks whether an element is visible, while elementToBeClickable() is intended for elements that need to be ready for clicking.

104. Interview Question: Why Is Thread.sleep() Not Preferred?

Thread.sleep() waits for a fixed duration without checking application state. Condition-based waits are generally more efficient and reliable for dynamic web applications.

105. Interview Question: How Do You Wait for an Alert?

Alert alert = wait.until(

    ExpectedConditions.alertIsPresent()

);

 

alert.accept();

106. Interview Question: How Do You Wait for an Iframe?

wait.until(

    ExpectedConditions.frameToBeAvailableAndSwitchToIt(

        By.id("frame")

    )

);

107. Interview Question: How Do You Wait for a Loader to Disappear?

wait.until(

    ExpectedConditions.invisibilityOfElementLocated(

        By.id("loader")

    )

);

108. Interview Question: How Do You Wait for URL Change?

wait.until(

    ExpectedConditions.urlContains(

        "/dashboard"

    )

);

109. Interview Question: How Do You Handle Stale Elements?

Re-locate the element after the DOM update and use appropriate synchronization. Conditions such as stalenessOf() and refreshed() can also be useful depending on the scenario.

110. Interview Question: Can We Use Multiple Explicit Waits?

Yes. Different waits can be created with different timeout values when different application conditions require different synchronization behavior.

111. Quick Revision Table

ConceptKey Point
Implicit WaitGlobal element lookup timeout.
Explicit WaitWaits for a specific condition.
WebDriverWaitCommon Selenium Java implementation of explicit waiting.
FluentWaitConfigurable timeout, polling, and exception handling.
ExpectedConditionsPredefined Selenium wait conditions.
presenceOfElementLocated()Waits for DOM presence.
visibilityOfElementLocated()Waits for visibility.
elementToBeClickable()Waits for click readiness.
invisibilityOfElementLocated()Waits for an element to disappear.
textToBePresentInElementLocated()Waits for expected text.
alertIsPresent()Waits for an alert.
frameToBeAvailableAndSwitchToIt()Waits for a frame and switches to it.
stalenessOf()Waits for an old element reference to become stale.
refreshed()Re-evaluates a condition after DOM refresh.
Thread.sleep()Fixed delay; not condition-based.

112. Final Summary

Waits are essential for creating stable and reliable Selenium automation scripts with Java. Modern web applications frequently load elements asynchronously, update the DOM dynamically, display loaders, open frames and windows, and change content after API responses.

Implicit waits provide a basic global synchronization mechanism for element lookup, while explicit waits provide precise condition-based synchronization. WebDriverWait is commonly used for explicit waits, and FluentWait provides additional control over polling intervals and ignored exceptions.

The most important principle is to wait for the application state rather than an arbitrary amount of time. Instead of using Thread.sleep() repeatedly, automation engineers should wait for meaningful conditions such as visibility, clickability, text, URL, title, alert presence, frame availability, element count, or custom application state.

Professional Selenium frameworks commonly centralize wait logic in reusable utilities and Page Object classes. Correct wait usage reduces flaky tests, improves execution efficiency, and makes automation code easier to understand and maintain.

113. Course Resources

Learn Selenium WebDriver, Java automation, waits, locators, Page Object Model, TestNG, framework development, and practical automation through structured Selenium training resources:


114. One-Line Revision

Selenium Waits = Synchronizing Java automation with the application's actual state by waiting for elements, text, URLs, frames, alerts, windows, DOM changes, or other required conditions before performing the next action.

whatsapp